// pages/goods/detail/index.js
import { getGoodsDetailsApi } from '../../../api/goods'
import { AddtoCartApi, getCartListApi } from '@/api/cart'
import { userBehavior } from '../../../behaviors/userBehavior'
Page({
  behaviors: [userBehavior],
  // 页面的初始数据
  data: {
    goodsInfo: {}, // 商品详情
    show: false, // 控制加入购物车和立即购买弹框的显示
    count: 1, // 商品购买数量，默认是 1
    blessing: '', // 祝福语
    buyNow: 0, //0加入购物车
    allCount: ''
  },
  previewImg() {
    wx.previewImage({
      urls: this.data.goodsInfo.detailList
    })
  },
  async getGoodsDetails() {
    const res = await getGoodsDetailsApi(this.goodsId)
    // console.log(res)
    this.setData({
      goodsInfo: res.data
    })
  },
  onLoad(options) {
    this.goodsId = options.goodsId
    this.getGoodsDetails()
    this.getCartCount()
  },
  async getCartCount() {
    const { token } = this.data
    if (!token) {
      return
    } else {
      const res = await getCartListApi()
      // console.log(res)
      if (res.data.length) {
        let sum = 0
        res.data.forEach((item) => {
          sum += item.count
        })
        this.setData({
          allCount: (sum > 99 ? '99+' : sum) + '' //类型转换为string
        })
      }
    }
  },
  // 加入购物车
  handleAddcart() {
    this.setData({
      show: true,
      buyNow: 0
    })
  },

  // 立即购买
  handeGotoBuy() {
    this.setData({
      show: true,
      buyNow: 1
    })
  },

  // 点击关闭弹框时触发的回调
  onClose() {
    this.setData({ show: false })
  },

  // 监听是否更改了购买数量
  onChangeGoodsCount(event) {
    console.log(event.detail)
    this.setData({
      count: Number(event.detail)
    })
  },
  async handleSubmit() {
    const { token, count, blessing, buyNow } = this.data
    const goodsId = this.goodsId
    if (!blessing.trim()) {
      wx.toast({
        title: '祝福语不能为空'
      })
      return
    }
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      this.setData({
        show: false
      })
      return
    }

    if (buyNow === 0) {
      const res = await AddtoCartApi({ goodsId, count, blessing })
      // console.log(res)
      if (res.code === 200) {
        wx.toast({ title: '加入购物车成功' })
        this.getCartCount()
        this.setData({
          show: false
        })
      }
    } else {
      wx.navigateTo({
        url: `/modules/orderPayModule/pages/order/detail/detail?goodsId=${goodsId}&blessing=${blessing}`
      })
    }
  },
  onShareAppMessage() {
    return {
      title: '所有的怦然心动，都是你',
      path: '/pages/index/index',
      imageUrl: '../../assets/images/love.jpg'
    }
  },
  // 转发到朋友圈功能
  onShareTimeline() {}
})
